﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;

namespace FlyComet
{
    public class AsyncRequestState : IAsyncResult
    {
        public AsyncRequestState(HttpContext ctx, AsyncCallback cb, object extraData)
        {
            _ctx = ctx;
            _cb = cb;
            _extraData = extraData;
        }

        private HttpContext _ctx;

        internal HttpContext Context
        {
            get { return _ctx; }
            set { _ctx = value; }
        }
        private AsyncCallback _cb;

        internal AsyncCallback CallBack
        {
            get { return _cb; }
            set { _cb = value; }
        }
        private object _extraData;

        internal object ExtraData
        {
            get { return _extraData; }
            set { _extraData = value; }
        }
        private bool _isCompleted = false;
        private ManualResetEvent _callCompleteEvent = null;

        internal void CompleteRequest()
        {
            _isCompleted = true;
            lock (this)
            {
                if (_callCompleteEvent != null)
                    _callCompleteEvent.Set();
            }
            // if a callback was registered, invoke it now
            if (_cb != null)
                _cb(this);
        }

        // IAsyncResult interface property implementations
        public object AsyncState
        { get { return (_extraData); } }
        public bool CompletedSynchronously
        { get { return (false); } }
        public bool IsCompleted
        { get { return (_isCompleted); } }
        public WaitHandle AsyncWaitHandle
        {
            get
            {
                lock (this)
                {
                    if (_callCompleteEvent == null)
                        _callCompleteEvent = new ManualResetEvent(false);

                    return _callCompleteEvent;
                }
            }
        }
    }
}